<template>
  <div class="modal-mask">
    <div class="modal-container">
      <button class="close-button" @click="$emit('close')">×</button>
      <h3 class="modal-title">找回密码</h3>
      <el-form :model="forgotForm" class="forgot-form">
        <el-form-item>
          <el-input
            placeholder="请输入有效的手机号/邮箱"
            v-model="forgotForm.identifier"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="输入8~16位新密码，区分大小写"
            type="password"
            v-model="forgotForm.newPassword"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="请输入验证码" v-model="forgotForm.code">
            <template #append>
              <el-button type="primary" @click="getCode" class="get-code-button">
                获取验证码
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-button type="primary" block class="login-button" @click="resetPassword">
          修改并登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      forgotForm: {
        identifier: "", // 手机号或邮箱
        newPassword: "", // 新密码
        code: "", // 验证码
      },
    };
  },
  methods: {
    /**
     * 判断是否为手机号
     */
    isPhone(input) {
      const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号正则
      return phoneRegex.test(input);
    },

    /**
     * 判断是否为邮箱
     */
    isEmail(input) {
      const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
      return emailRegex.test(input);
    },

    /**
     * 获取验证码（根据手机号或邮箱）
     */
    async getCode() {
      const identifier = this.forgotForm.identifier.trim();

      if (this.isPhone(identifier)) {
        // 调用手机号验证码发送接口
        try {
          const response = await fetch(`/api/api/sms/send?phone=${encodeURIComponent(identifier)}`, {
            method: "GET",
          });

          const result = await response.json();
          if (result.code === "200") {
            alert(`验证码已发送到手机号: ${identifier}`);
          } else {
            alert(`发送验证码失败: ${result.message}`);
          }
        } catch (error) {
          console.error("发送手机号验证码失败:", error);
          alert("发送验证码失败，请稍后重试！");
        }
      } else if (this.isEmail(identifier)) {
        // 调用邮箱验证码发送接口
        try {
          const response = await fetch(`/api/api/email/send?email=${encodeURIComponent(identifier)}`, {
            method: "GET",
          });

          const result = await response.json();
          if (result.code === "200") {
            alert(`验证码已发送到邮箱: ${identifier}`);
          } else {
            alert(`发送验证码失败: ${result.message}`);
          }
        } catch (error) {
          console.error("发送邮箱验证码失败:", error);
          alert("发送验证码失败，请稍后重试！");
        }
      } else {
        alert("请输入有效的手机号或邮箱！");
      }
    },

    /**
     * 重置密码
     */
    async resetPassword() {
      const { identifier, newPassword, code } = this.forgotForm;

      if (!identifier || !newPassword || !code) {
        alert("请输入完整的信息！");
        return;
      }
      if (this.isPhone(identifier)) {
        try {
          const response = await fetch(`/api/api/password/phone?phone=${this.forgotForm.identifier}&code=${this.forgotForm.code}&newPassword=${this.forgotForm.newPassword}`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ identifier, newPassword, code }),
          });

          const result = await response.json();
          if (result.code === "200") {
            alert("密码重置成功，请重新登录！");
            this.$emit("reset-success");
            this.$emit("close");
          } else {
            alert(`重置失败: ${result.message}`);
          }
        } catch (error) {
          console.error("密码重置失败:", error);
          alert("重置失败，请稍后重试！");
        }
      } else if (this.isEmail(identifier)) {
        try {
          const response = await fetch(`/api/api/password/email?email=${this.forgotForm.identifier}&code=${this.forgotForm.code}&newPassword=${this.forgotForm.newPassword}`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ identifier, newPassword, code }),
          });

          const result = await response.json();
          if (result.code === "200") {
            alert("密码重置成功，请重新登录！");
            this.$emit("reset-success");
            this.$emit("close");
          } else {
            alert(`重置失败: ${result.message}`);
          }
        } catch (error) {
          console.error("密码重置失败:", error);
          alert("重置失败，请稍后重试！");
        }
      }

    },
  },
};
</script>

<style scoped>
.modal-mask {
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-container {
  width: 400px;
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  position: relative;
}

.close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  border: none;
  background: none;
  font-size: 20px;
  cursor: pointer;
}

.modal-title {
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
}

.get-code-button {
  height: 40px;
  padding: 0 15px;
  font-size: 14px;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}
</style>
